const request=require("superagent");
const cheerio = require('cheerio');
const iconv = require('iconv-lite');
const util = require('util');
const charset = require("superagent-charset")(request);
const fs=require('fs');
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : '127.0.0.1',
  user     : 'root',
  password : 'f9fe8cd75990fffe',
  database : 'b.com'
});
connection.query = util.promisify(connection.query);
function delay(t){
    return new Promise(resolve => setTimeout(resolve, t))
}
async function downImage(id,url){
	let u=url;
	let name=u.substring(u.lastIndexOf("/")+1);
	let path="./image/"+name;
	console.log(id,u,name);
	let res=await request.get(u);
	let r=await fs.writeFileSync(path,res.body,"binary");
	let sql=`update tplay_attachment set filepath =? where id=?`;
	let filepath="/upload/image/"+name;
	let result=await connection.query(sql,[filepath,id]);
	return {id:id,path:path};
}
async function updateBookImage(){
	let sql=`select * from tplay_attachment where id>1 order by id`;
	let result=await connection.query(sql);
	// console.log(result);
	for(let o of result){
		// await delay(200);
		console.log(`downloading cover of ${o.id}`);
		try{
			let path=await downImage(o.id,o.filepath);
		}catch(e){
			console.log('error',o.id,e);
		}	 
	}
	connection.end();
}
updateBookImage();